<template>
  <div class="min-h-screen bg-gray-50">
    <!-- 加载状态 -->
    <div v-if="loading" class="flex justify-center items-center min-h-screen">
      <div class="text-center">
        <div class="inline-block animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600"></div>
        <p class="mt-2 text-gray-500">加载中...</p>
      </div>
    </div>

    <!-- 错误状态 -->
    <div v-else-if="error" class="flex justify-center items-center min-h-screen">
      <div class="text-center">
        <div class="mx-auto w-16 h-16 bg-red-100 rounded-full flex items-center justify-center mb-4">
          <svg class="w-8 h-8 text-red-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path>
          </svg>
        </div>
        <h3 class="text-lg font-semibold text-gray-900 mb-2">加载失败</h3>
        <p class="text-gray-500 mb-4">{{ error }}</p>
        <button 
          @click="loadEbook"
          class="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors"
        >
          重试
        </button>
      </div>
    </div>

    <!-- 主要内容 -->
    <div v-else-if="ebook" class="container mx-auto px-4 py-8">
      <!-- 返回按钮 -->
      <div class="mb-6">
        <button 
          @click="$router.go(-1)"
          class="flex items-center text-gray-600 hover:text-gray-800 transition-colors"
        >
          <svg class="w-5 h-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7"></path>
          </svg>
          返回
        </button>
      </div>

      <div class="grid grid-cols-1 lg:grid-cols-3 gap-8">
        <!-- 左侧：电子书信息 -->
        <div class="lg:col-span-2">
          <div class="bg-white rounded-lg shadow-sm p-8">
            <!-- 电子书封面和基本信息 -->
            <div class="flex flex-col md:flex-row gap-6 mb-8">
              <div class="flex-shrink-0">
                <div class="w-48 h-64 bg-gradient-to-br from-blue-500 to-purple-600 rounded-lg flex items-center justify-center">
                  <div class="text-white text-center">
                    <svg class="w-16 h-16 mx-auto mb-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 6.253v13m0-13C10.832 5.477 9.246 5 7.5 5S4.168 5.477 3 6.253v13C4.168 18.477 5.754 18 7.5 18s3.332.477 4.5 1.253m0-13C13.168 5.477 14.754 5 16.5 5c1.746 0 3.332.477 4.5 1.253v13C19.832 18.477 18.246 18 16.5 18c-1.746 0-3.332.477-4.5 1.253"></path>
                    </svg>
                    <span class="text-sm font-medium">{{ ebook.format }}</span>
                  </div>
                </div>
              </div>

              <div class="flex-1">
                <h1 class="text-3xl font-bold text-gray-900 mb-4">{{ ebook.title }}</h1>
                
                <div class="flex flex-wrap gap-2 mb-4">
                  <span class="px-3 py-1 bg-blue-100 text-blue-800 rounded-full text-sm font-medium">
                    {{ getCategoryName(ebook.category) }}
                  </span>
                  <span class="px-3 py-1 bg-green-100 text-green-800 rounded-full text-sm font-medium">
                    {{ ebook.format }}
                  </span>
                  <span class="px-3 py-1 bg-purple-100 text-purple-800 rounded-full text-sm font-medium">
                    {{ ebook.pages }} 页
                  </span>
                </div>

                <div class="text-gray-600 mb-4">
                  <p class="mb-2"><span class="font-medium">作者：</span>{{ ebook.author }}</p>
                  <p class="mb-2"><span class="font-medium">出版社：</span>{{ ebook.publisher || '未知' }}</p>
                  <p class="mb-2"><span class="font-medium">出版年份：</span>{{ ebook.publish_date || '未知' }}</p>
                  <p class="mb-2"><span class="font-medium">语言：</span>{{ ebook.language || '中文' }}</p>
                </div>

                <!-- 统计信息 -->
                <div class="flex items-center space-x-6 text-sm text-gray-500 mb-6">
                  <span class="flex items-center">
                    <svg class="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"></path>
                      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"></path>
                    </svg>
                    {{ ebook.views }} 次浏览
                  </span>
                  <span class="flex items-center">
                    <svg class="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4.318 6.318a4.5 4.5 0 000 6.364L12 20.364l7.682-7.682a4.5 4.5 0 00-6.364-6.364L12 7.636l-1.318-1.318a4.5 4.5 0 00-6.364 0z"></path>
                    </svg>
                    {{ ebook.likes }} 次点赞
                  </span>
                  <span class="flex items-center">
                    <svg class="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 10v6m0 0l-3-3m3 3l3-3m2 8H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"></path>
                    </svg>
                    {{ ebook.downloads }} 次下载
                  </span>
                </div>

                <!-- 评分 -->
                <div v-if="ebook.rating" class="flex items-center mb-6">
                  <div class="flex items-center">
                    <div class="flex text-yellow-400">
                      <svg v-for="i in 5" :key="i" class="w-5 h-5" :class="i <= Math.round(ebook.rating) ? 'fill-current' : 'text-gray-300'" fill="currentColor" viewBox="0 0 24 24">
                        <path d="M12 2l3.09 6.26L22 9.27l-5 4.87 1.18 6.88L12 17.77l-6.18 3.25L7 14.14 2 9.27l6.91-1.01L12 2z"/>
                      </svg>
                    </div>
                    <span class="ml-2 text-gray-600">{{ ebook.rating.toFixed(1) }} ({{ ebook.rating_count }} 人评价)</span>
                  </div>
                </div>
              </div>
            </div>

            <!-- 电子书描述 -->
            <div class="mb-8">
              <h2 class="text-xl font-semibold text-gray-900 mb-4">内容简介</h2>
              <p class="text-gray-600 leading-relaxed">{{ ebook.description }}</p>
            </div>

            <!-- 标签 -->
            <div v-if="ebook.tags && ebook.tags.length > 0" class="mb-8">
              <h2 class="text-xl font-semibold text-gray-900 mb-4">标签</h2>
              <div class="flex flex-wrap gap-2">
                <span
                  v-for="tag in ebook.tags"
                  :key="tag.id"
                  class="px-3 py-1 bg-gray-100 text-gray-700 rounded-full text-sm"
                >
                  {{ tag.name }}
                </span>
              </div>
            </div>
          </div>
        </div>

        <!-- 右侧：操作面板 -->
        <div class="lg:col-span-1">
          <div class="bg-white rounded-lg shadow-sm p-6 sticky top-8">
            <h3 class="text-lg font-semibold text-gray-900 mb-4">操作</h3>
            
            <!-- 下载按钮 -->
            <button
              @click="downloadEbook"
              :disabled="downloading"
              class="w-full bg-blue-600 text-white py-3 px-4 rounded-lg hover:bg-blue-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors mb-4"
            >
              {{ downloading ? '下载中...' : '下载电子书' }}
            </button>

            <!-- 点赞按钮 -->
            <button
              @click="toggleLike"
              :disabled="liking"
              class="w-full bg-gray-100 text-gray-700 py-3 px-4 rounded-lg hover:bg-gray-200 disabled:opacity-50 disabled:cursor-not-allowed transition-colors mb-4"
            >
              {{ liking ? '处理中...' : (ebook.is_liked ? '取消点赞' : '点赞') }}
            </button>

            <!-- 评分 -->
            <div class="mb-4">
              <h4 class="text-sm font-medium text-gray-700 mb-2">我的评分</h4>
              <div class="flex items-center">
                <div class="flex text-yellow-400">
                  <button
                    v-for="i in 5"
                    :key="i"
                    @click="rateEbook(i)"
                    :disabled="rating"
                    class="w-6 h-6 hover:scale-110 transition-transform disabled:opacity-50 disabled:cursor-not-allowed"
                  >
                    <svg class="w-full h-full" :class="i <= (userRating || 0) ? 'fill-current' : 'text-gray-300'" fill="currentColor" viewBox="0 0 24 24">
                      <path d="M12 2l3.09 6.26L22 9.27l-5 4.87 1.18 6.88L12 17.77l-6.18 3.25L7 14.14 2 9.27l6.91-1.01L12 2z"/>
                    </svg>
                  </button>
                </div>
                <span v-if="userRating" class="ml-2 text-sm text-gray-600">{{ userRating }} 星</span>
              </div>
            </div>

            <!-- 分享 -->
            <div>
              <h4 class="text-sm font-medium text-gray-700 mb-2">分享</h4>
              <div class="flex space-x-2">
                <button
                  @click="shareToWechat"
                  class="flex-1 bg-green-500 text-white py-2 px-3 rounded text-sm hover:bg-green-600 transition-colors"
                >
                  微信
                </button>
                <button
                  @click="shareToWeibo"
                  class="flex-1 bg-red-500 text-white py-2 px-3 rounded text-sm hover:bg-red-600 transition-colors"
                >
                  微博
                </button>
                <button
                  @click="copyLink"
                  class="flex-1 bg-gray-500 text-white py-2 px-3 rounded text-sm hover:bg-gray-600 transition-colors"
                >
                  复制链接
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 用户评价 -->
      <div v-if="ratings.length > 0" class="mt-8">
        <div class="bg-white rounded-lg shadow-sm p-8">
          <h2 class="text-xl font-semibold text-gray-900 mb-6">用户评价</h2>
          <div class="space-y-4">
            <div
              v-for="rating in ratings"
              :key="rating.id"
              class="border-b border-gray-200 pb-4 last:border-b-0"
            >
              <div class="flex items-center justify-between mb-2">
                <div class="flex items-center">
                  <img
                    :src="rating.user?.avatar || '/static/avatar/default.jpg'"
                    :alt="rating.user?.username"
                    class="w-8 h-8 rounded-full mr-3"
                  >
                  <span class="font-medium text-gray-900">{{ rating.user?.username || '匿名用户' }}</span>
                </div>
                <div class="flex items-center">
                  <div class="flex text-yellow-400 mr-2">
                    <svg v-for="i in 5" :key="i" class="w-4 h-4" :class="i <= rating.rating ? 'fill-current' : 'text-gray-300'" fill="currentColor" viewBox="0 0 24 24">
                      <path d="M12 2l3.09 6.26L22 9.27l-5 4.87 1.18 6.88L12 17.77l-6.18 3.25L7 14.14 2 9.27l6.91-1.01L12 2z"/>
                    </svg>
                  </div>
                  <span class="text-sm text-gray-500">{{ formatDate(rating.created_at) }}</span>
                </div>
              </div>
              <p v-if="rating.comment" class="text-gray-600">{{ rating.comment }}</p>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import { EbookAPI, type Ebook, type EbookRating } from '@/api/ebook'

const route = useRoute()

// 响应式数据
const ebook = ref<Ebook | null>(null)
const ratings = ref<EbookRating[]>([])
const loading = ref(false)
const error = ref('')
const downloading = ref(false)
const liking = ref(false)
const rating = ref(false)
const userRating = ref(0)

// 方法
const loadEbook = async () => {
  try {
    loading.value = true
    error.value = ''
    
    const ebookId = Number(route.params.id)
    const [ebookRes, ratingsRes] = await Promise.all([
      EbookAPI.getEbook(ebookId),
      EbookAPI.getEbookRatings(ebookId)
    ])
    
    ebook.value = ebookRes
    ratings.value = ratingsRes.items || []
  } catch (err: any) {
    error.value = err.message || '加载电子书失败'
    console.error('加载电子书失败:', err)
  } finally {
    loading.value = false
  }
}

const downloadEbook = async () => {
  if (!ebook.value) return
  
  try {
    downloading.value = true
    const downloadInfo = await EbookAPI.downloadEbook(ebook.value.id)
    
    // 创建下载链接
    const link = document.createElement('a')
    link.href = downloadInfo.download_url
    link.download = downloadInfo.file_name
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    
    // 更新下载次数
    ebook.value.downloads += 1
  } catch (err: any) {
    console.error('下载失败:', err)
    alert(err.message || '下载失败')
  } finally {
    downloading.value = false
  }
}

const toggleLike = async () => {
  if (!ebook.value) return
  
  try {
    liking.value = true
    await EbookAPI.likeEbook(ebook.value.id)
    
    // 更新本地状态
    ebook.value.is_liked = !ebook.value.is_liked
    ebook.value.likes += ebook.value.is_liked ? 1 : -1
  } catch (err: any) {
    console.error('点赞失败:', err)
    alert(err.message || '操作失败')
  } finally {
    liking.value = false
  }
}

const rateEbook = async (ratingValue: number) => {
  if (!ebook.value) return
  
  try {
    rating.value = true
    await EbookAPI.rateEbook(ebook.value.id, { rating: ratingValue })
    userRating.value = ratingValue
    
    // 重新加载评分数据
    const ratingsRes = await EbookAPI.getEbookRatings(ebook.value.id)
    ratings.value = ratingsRes.items || []
  } catch (err: any) {
    console.error('评分失败:', err)
    alert(err.message || '评分失败')
  } finally {
    rating.value = false
  }
}

const getCategoryName = (category: string): string => {
  const categoryMap: { [key: string]: string } = {
    algorithm: '算法',
    'data-structure': '数据结构',
    programming: '编程语言',
    system: '系统设计',
    ai: '人工智能',
    database: '数据库'
  }
  return categoryMap[category] || category
}

const formatDate = (dateString: string): string => {
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN')
}

const shareToWechat = () => {
  // 微信分享逻辑
  console.log('分享到微信')
}

const shareToWeibo = () => {
  // 微博分享逻辑
  console.log('分享到微博')
}

const copyLink = () => {
  navigator.clipboard.writeText(window.location.href)
  alert('链接已复制到剪贴板')
}

onMounted(() => {
  loadEbook()
})
</script>

